package com.bl.andr.utillib;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import androidx.core.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.ReplacementSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.widget.TextView;

/**
 * 操作字符串部分文字的颜色，下划线，删除线，点击事件等等
 * 包含起始位置，不包含结束位置
 * Created by yubaolin on 2016/12/6 0006.
 */

public class SSBUtil {

    private Builder mBuilder;

    private SSBUtil(Builder builder) {
        mBuilder = builder;
    }

    /**
     * 设置删除线,删除线和文字颜色一致
     */
    public void setDeleteSpan(TextView tv) {
        if (tv == null) return;
        tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        //tv.getPaint().setStrikeThruText(true);
    }

    /**
     * 最后一步调用
     */
    public SSBUtil updateTextView(TextView textView) {
        if (mBuilder.ssb != null)
            textView.setText(mBuilder.ssb);
        return this;
    }

    /**
     * 设置超链接为可点击状态
     * 有点击事件时最后调用
     */
    public SSBUtil setLinkMovement(TextView textView) {
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        return this;
    }


    public class Builder {

        private Context context;
        private SpannableStringBuilder ssb;

        public Builder(Context context) {
            this.context = context;
        }

        /**
         * 第一步调用
         */
        public Builder setSSB(String content) {
            ssb = new SpannableStringBuilder(content);
            return this;
        }

        public Builder setSSB(int strId) {
            setSSB(ResUtil.getStr(context, strId));
            return this;
        }

        /**
         * 设置前景色
         */
        public Builder setForColorSpan(int colorRes, int startPos, int endPos) {
            if (ssb != null) {
                ForegroundColorSpan colorSpan = new ForegroundColorSpan(
                        ContextCompat.getColor(context, colorRes)
                );
                ssb.setSpan(colorSpan, startPos, endPos, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
            return this;
        }

        /**
         * 设置背景色
         */
        public Builder setBackColorSpan(int colorRes, int startPos, int endPos) {
            if (ssb != null) {
                BackgroundColorSpan colorSpan = new BackgroundColorSpan(
                        ContextCompat.getColor(context, colorRes)
                );
                ssb.setSpan(colorSpan, startPos, endPos, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
            return this;
        }

        /**
         * 设置删除线
         */
        public Builder setDeleteSpan(int startPos, int endPos) {
            if (ssb != null) {
                StrikethroughSpan stSpan = new StrikethroughSpan();
                ssb.setSpan(stSpan, startPos, endPos, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
            return this;
        }


        /**
         * 字体样式
         *
         * @param family 字体的样式
         * @param style  style 为0 即是正常的，还有Typeface.BOLD(粗体) Typeface.ITALIC(斜体)等
         * @param size   size  为0 即采用原始的正常的 size大小
         * @return
         */
        public Builder setTextAppearanceSpan(String family, int style, int size, int colorRes, int startPos, int endPos) {
            if (ssb != null) {
                ColorStateList colorStateList = ContextCompat.getColorStateList(context, colorRes);
                TextAppearanceSpan span = new TextAppearanceSpan(family, style, size, colorStateList, null);
                ssb.setSpan(span, startPos, endPos, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }

            return this;
        }


        public Builder setClickSpan(final boolean hasUnderLine, final int linkColor, int startPos, int endPos,
                                    final ClickListener listener) {
            if (ssb != null) {
                ClickableSpan clickSpan = new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        listener.onClickText();
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setUnderlineText(hasUnderLine);//去掉下划线
                        ds.setColor(ContextCompat.getColor(context, linkColor));
                    }
                };
                ssb.setSpan(clickSpan, startPos, endPos, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }

            return this;
        }


        /**
         * 设置文字相对大小，指相对于文本设定的大小的相对比例。
         *
         * @param proportion 大小比例
         */
        public Builder setRelativeSizeSpan(float proportion, int startPos, int endPos) {
            if (ssb != null) {
                RelativeSizeSpan sizeSpan = new RelativeSizeSpan(proportion);
                ssb.setSpan(sizeSpan, startPos, endPos, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
            return this;
        }

        /**
         * 设置圆角背景
         */
        public Builder setRoundBackSpan(int colorRes, int startPos, int endPos) {
            if (ssb != null) {
                RoundBackgroundColorSpan span = new RoundBackgroundColorSpan(context,
                        ContextCompat.getColor(context, colorRes)
                );
                ssb.setSpan(span, startPos, endPos, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }

            return this;
        }

        public SSBUtil build() {
            return new SSBUtil(this);
        }
    }


    public interface ClickListener {
        void onClickText();
    }

    private class RoundBackgroundColorSpan extends ReplacementSpan {
        private int bgColor;
        private int textColor;
        private Context context;

        public RoundBackgroundColorSpan(Context context, int bgColor, int textColor) {
            super();
            this.context = context;
            this.bgColor = bgColor;
            this.textColor = textColor;
        }

        public RoundBackgroundColorSpan(Context context, int bgColor) {
            this(context, bgColor, Color.WHITE);
        }

        /**
         * 返回文字大小
         */
        @Override
        public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
            return ((int) paint.measureText(text, start, end) + 60);
        }

        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
            int color1 = paint.getColor();
            paint.setColor(this.bgColor);

            RectF rectF = new RectF(x, top + 1, x + ((int) paint.measureText(text, start, end) + 40), bottom - 1);
            canvas.drawRoundRect(rectF, 15, 15, paint);
            paint.setColor(this.textColor);

            // 文本14sp ，选中文本 14sp*0.8

            float fontSize = sp2px(context, 14) * 0.8f;
            canvas.drawText(text, start, end, x + 20, rectF.bottom - (rectF.bottom - rectF.top - fontSize) / 2 - 5, paint);
            paint.setColor(color1);
        }

        /**
         * 将sp值转换为px值，保证文字大小不变
         *
         * @param spValue
         * @return
         */
        private float sp2px(Context context, float spValue) {
            final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
            return spValue * fontScale + 0.5f;
        }
    }


}
